﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using The_LarX;
using System.IO;
using System.Reflection;
using Microsoft.Xna.Framework.Input;
using LarX_Windows.WinForms;
using LarX_Windows.Update;
using SynapseGaming.LightingSystem.Lights;
using Microsoft.Xna.Framework;
using SynapseGaming.LightingSystem.Shadows;
using LarX_Windows.Serial;
using LarX_Windows;
using Invasion_Barricade;
using System.Media;

namespace LarX_Editor
{
    public partial class MainForm : Form
    {
        private bool Remember_ModelCannotBeAnimatedModel = false;
        private bool Remember_AnimatedModelCanotBeModel = false;

        public static MainForm ActiveMainForm;

        public bool CanSave = true;

        public MainForm(string[] args)
        {
            ActiveMainForm = this;

            InitializeComponent();

            DirectoryInfo dir = new DirectoryInfo("Content");
            if (!dir.Exists)
            {
                MessageBox.Show("Content folder was not found, the Engine needs it for loading."
                + "The Editor is going to close now");
                this.Close();
                return;
            }
            assets_List.Items.Clear();
            GetFiles(dir);

            renderControl1.PropGrid = propertyGrid;

            if (args.Length > 0)
            {
                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i].EndsWith(".larscene"))
                    {
                        LoadScene(args[i]);
                    }
                    else if (args[i].EndsWith(".larlang"))
                    {
                        LanguageMainForm lang = new LanguageMainForm(args);
                    }
                }
            }
        }

        #region Assets List

        #region GetFiles
        private void GetFiles(DirectoryInfo dir)
        {
            DirectoryInfo[] Folders = dir.GetDirectories();
            FileInfo[] Files = dir.GetFiles();

            for (int i = 0; i < Files.Length; i++)
            {
                string s = Files[i].FullName;
                int content = s.IndexOf("Content");
                string newstring = s.Remove(0, content);
                string ultranew = newstring.Remove(0, 8);
                string megaultranew = ultranew;
                if (ultranew.Contains(".xnb"))
                {
                    megaultranew = ultranew.Remove(ultranew.Length - 4, 4);
                }
                assets_List.Items.Add(megaultranew);
            }
            for (int i = 0; i < Folders.Length; i++)
            {
                GetFiles(Folders[i]);
            }
        }
        #endregion

        #region Mouse Doble Click
        private void assets_List_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            try
            {
                string item = (string)assets_List.SelectedItem;
                Clipboard.SetText(item);
                toolStripStatusLabel1.Text = "Copied item " + '"' + item + '"';
            }
            catch { }
            /*
            try
            {
                if (assets_List.SelectedItem != null)
                {
                    string item = (string)assets_List.SelectedItem;
                    string fileName = Path.GetFileNameWithoutExtension(item);
                    bool Setted = false;
                    if (propertyGrid.SelectedObject != null)
                    {
                        if (fileName.StartsWith("tex_"))
                        {
                            Type ObjectType = propertyGrid.SelectedObject.GetType();
                            PropertyInfo[] info = ObjectType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
                            for (int i = 0; i < info.Length; i++)
                            {
                                if (info[i].Name == "TextureName" || info[i].Name == "ShapeName")
                                {
                                    info[i].SetValue(propertyGrid.SelectedObject, item, null);
                                    propertyGrid.Refresh();
                                    Setted = true;
                                }
                            }

                        }
                        if (fileName.StartsWith("model_"))
                        {
                            Type ObjectType = propertyGrid.SelectedObject.GetType();
                            PropertyInfo[] info = ObjectType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
                            for (int i = 0; i < info.Length; i++)
                            {
                                if (info[i].Name == "ModelName")
                                {
                                    if (!Remember_ModelCannotBeAnimatedModel)
                                    {
                                        if (MessageBox.Show("WARNING: The Actor class requires a MODEL to be used." +
                                            " If you try using an ANIMATED model, there is going to be an Exeption.",
                                            "WARNING", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                                        {
                                            return;
                                        }
                                        Remember_ModelCannotBeAnimatedModel = true;
                                    }
                                    info[i].SetValue(propertyGrid.SelectedObject, item, null);
                                    propertyGrid.Refresh();
                                    Setted = true;
                                }
                            }
                        }
                        if (fileName.StartsWith("animated_"))
                        {
                            Type ObjectType = propertyGrid.SelectedObject.GetType();
                            PropertyInfo[] info = ObjectType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
                            for (int i = 0; i < info.Length; i++)
                            {
                                if (info[i].Name == "ModelName")
                                {
                                    if (!Remember_AnimatedModelCanotBeModel)
                                    {
                                        if (MessageBox.Show("WARNING: The AnimatedActor class requires" +
                                            " an ANIMATED MODEL to be used. If you try using a normal MODEL," +
                                            " there is going to be an Exeption.",
                                            "WARNING", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                                        {
                                            return;
                                        }
                                        Remember_AnimatedModelCanotBeModel = true;
                                    }
                                    info[i].SetValue(propertyGrid.SelectedObject, item, null);
                                    propertyGrid.Refresh();
                                    Setted = true;
                                }
                            }
                        }
                    }
                    if (!Setted && propertyGrid.SelectedObject != null)
                    {
                        if (MessageBox.Show("Couldn't find any property that applies to file." +
                        " Copy Asset Place to clipboard?", "WARNING", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            Clipboard.SetText(item);
                        }
                    }
                    if (!Setted && propertyGrid.SelectedObject == null)
                    {
                        if (MessageBox.Show("There is no selected object in the PropertyGrid." +
                         " Copy Asset Place to clipboard?", "WARNING", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            Clipboard.SetText(item);
                        }
                    }
                }
            }
            catch { }
             */
        }
        #endregion

        #endregion

        #region Add
        #region Actor
        private void actorPlayerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                GameScreen Screen = (GameScreen)Engine.GameScreens[0];
                ActorPlayer Player = new ActorPlayer(
                    new Actor("Engine\\Models\\model_cube"), renderControl1.Renderer, Screen);
                toolStripStatusLabel1.Text = "Created Actor";
            }
            catch { }
        }
        #endregion

        #region Camera
        #region 3D
        private FloatingCamera FloatingCamera;
        private void floatingCameraToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (renderControl1.Renderer == null)
                {
                    renderControl1.Renderer = new Renderer_SunBurn(renderControl1.Screen);
                    renderControl1.Renderer.BeforeTheSceneIsRendered = renderControl1.Renderer_StartDrawing;
                }
                if (Engine.Services.ContainsService(typeof(Camera3D)))
                {
                    Engine.Services.RemoveService(typeof(Camera3D));
                }
                GameScreen Screen = (GameScreen)Engine.GameScreens[0];
                FloatingCamera = new FloatingCamera(Engine.AspectRatio, Screen);
                renderControl1.Camera = FloatingCamera;                
            }
            catch (Exception exce)
            {
            }
        }
        private void targetCameraToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (Engine.Services.ContainsService(typeof(Camera3D)))
                {
                    Engine.Services.RemoveService(typeof(Camera3D));
                }
                GameScreen Screen = (GameScreen)Engine.GameScreens[0];
                TargetCamera Camera = new TargetCamera(Screen);
                Camera.Position = new Microsoft.Xna.Framework.Vector3(5);
                Engine.Services.AddService(typeof(Camera3D), Camera);
            }
            catch (Exception exce)
            {
            }
        }
        private void rotatedCameraToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                GameScreen Screen = (GameScreen)Engine.GameScreens[0];
                RotatedCamera Camera = new RotatedCamera(Screen);
                Camera.Renderer = renderControl1.Renderer;
            }
            catch (Exception exce)
            {
            }
        }
        #endregion                
        #endregion

        #region Light
        private void ambientLightToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AmbientLightSunBurn point = new AmbientLightSunBurn(renderControl1.Renderer, Engine.GameScreens[0]);
        }
        private void pointLightToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PointLightSunBurn point = new PointLightSunBurn(renderControl1.Renderer, Engine.GameScreens[0]);
        }

        private void directionalLightToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DirectionalLightSunBurn dir = new DirectionalLightSunBurn(renderControl1.Renderer, Engine.GameScreens[0]);
        }
        #endregion                

        #region Physics
        private void physicsSimulatorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Engine.Services.ContainsService(typeof(BepuPhysics)))
            {
                MessageBox.Show("There is already one instance of Physics" +
                    " running. Can't start another one");
                return;
            }
            if (!Engine.Services.ContainsService(typeof(BepuPhysics)))
            {
                BepuPhysics Physic = new BepuPhysics(Engine.GameScreens[0]);
                Engine.Services.AddService(typeof(BepuPhysics), Physic);
            }
        }
        private void physicCubeActorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!Engine.Services.ContainsService(typeof(BepuPhysics)))
            {
                MessageBox.Show("There is no Instance of BepuPhysics" +
                    " running. Start one if you want to create a Physic" +
                    " enabled object");
                return;
            }
            GameScreen Screen = (GameScreen)Engine.GameScreens[0];
            try
            {
                BepuActorPlayer Physic = new BepuActorPlayer(
                    new BepuEntity_Box(),
                    new Actor("Engine\\Models\\model_Cube"), renderControl1.Renderer,
                    Screen);
                Physic.Entity.Mass = 5;
                Physic.Entity.Immovable = true;
                Physic.Actor.Entity = Physic.Entity;
                Physic.Actor.ComponentParent = Physic;
            }
            catch (Exception exce)
            {
            }
        }
        private void physicsSphereActorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (CheckforBepuPhysics())
            {
                GameScreen Screen = (GameScreen)Engine.GameScreens[0];
                try
                {
                    BepuActorPlayer Physic = new BepuActorPlayer(
                        new BepuEntity_Sphere(),
                        new Actor("Engine\\Models\\model_Cube"), renderControl1.Renderer,
                        Screen);
                    Physic.Entity.Mass = 5;
                    Physic.Entity.Immovable = true;
                    Physic.Actor.Entity = Physic.Entity;
                    Physic.Actor.ComponentParent = Physic;
                }
                catch (Exception exce)
                {
                }
            }
        }
        private bool CheckforBepuPhysics()
        {
            if (!Engine.Services.ContainsService(typeof(BepuPhysics)))
            {
                MessageBox.Show("There is no Instance of BepuPhysics" +
                    " running. Start one if you want to create a Physic" +
                    " enabled object");
                return false;
            }
            return true;
        }
        #endregion

        #region Vegetation

        #region Modifiers

        private void windToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Wind wind = new Wind((Renderer_SunBurn)renderControl1.Renderer, Engine.GameScreens[0]);
        }

        #endregion

        #region Trees
        private void treeSimpleToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }
        private void treeAnimatedToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Tree_Animated tree = new Tree_Animated("palm2", "folha", "tree",
                (Renderer_SunBurn)renderControl1.Renderer, Engine.GameScreens[0]);
        }
        #endregion

        #endregion
        #endregion

        #region Transformation
        #region 3D
        private void button_Translation_Click(object sender, EventArgs e)
        {
            if (renderControl1.Manager != null)
            {
                renderControl1.Manager.Manipulation = ManipulationMode.Translation;
            }
        }
        private void button_Rotation_Click(object sender, EventArgs e)
        {
            if (renderControl1.Manager != null)
            {
                renderControl1.Manager.Manipulation = ManipulationMode.Rotation;
            }
        }
        private void button_Scale_Click(object sender, EventArgs e)
        {
            if (renderControl1.Manager != null)
            {
                renderControl1.Manager.Manipulation = ManipulationMode.Scale;
            }
        }
        #endregion        
        #endregion
        
        #region Property Grid
        private void propertyGrid_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
        {
            propertyGrid.Refresh();
        }
        #endregion

        #region Engine's Parameters
        private void button_select_Render_Click(object sender, EventArgs e)
        {
            propertyGrid.SelectedObject = Engine.RenderManager;
        }

        private The_LarX.VisualScriptEditor Editor;
        private void button_Select_VisualScript_Click(object sender, EventArgs e)
        {
            if (Editor == null)
            {
                Editor = new The_LarX.VisualScriptEditor(Engine.GameScreens[0]);
                Editor.OnRequestInformation += new EventHandler(Editor_OnRequestInformation);
                if (EngineSystem.VisualScripts.Count > 0)
                {
                    for (int i = 0; i < EngineSystem.VisualScripts.Count; i++)
                    {
                        if (!Editor.VisualScripts.Contains(EngineSystem.VisualScripts[i]))
                        {
                            Editor.VisualScripts.Add(EngineSystem.VisualScripts[i]);
                            foreach (VisualScript_Node node in EngineSystem.VisualScripts[i].Nodes)
                            {
                                node.StartRepresentation(Editor);
                            }
                        }
                    }
                }
            }
            else
            {
                Editor.Visible = !Editor.Visible;
            }
            Editor.SetProp = SetNodeToPropertyGrid;
        }
        void Editor_OnRequestInformation(object sender, EventArgs e)
        {
            NodeInformationHandler handler = new NodeInformationHandler(Editor.LastNodeInformation, Editor);
            handler.Show();
        }

        private void SetNodeToPropertyGrid(Object obj)
        {
            this.propertyGrid.SelectedObject = obj;
        }

        
        #endregion

        #region File Operations
        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Engine.Reset(false);
            renderControl1.LoadDefaultComps();
        }
        private void loadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = "LarX Scene Files|*.larscene";
            openFileDialog1.Title = "Select a LarX Scene File";

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                LoadScene(openFileDialog1.FileName);
            }
        }
        private void LoadScene(string sceneName)
        {
            Serializer.Merging = false;
            Engine.Reset(false);
            
            Serializer.Load(sceneName);
            Engine.PlayMode = false;
            renderControl1.LoadDefaultComps();

            if (EngineSystem.Actors.Count > 0)
            {
                //floatingCameraToolStripMenuItem_Click(null, null);

                renderControl1.Camera = FloatingCamera = new FloatingCamera(Engine.AspectRatio, renderControl1.Screen);
            }
        }
        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (CanSave)
            {
                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter = "LarX Scene Files|*.larscene";
                saveFileDialog1.Title = "Select a LarX Scene File";

                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    Serializer.Save(saveFileDialog1.FileName);
                }
            }
        }
        private void mergeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = "LarX Scene Files|*.larscene";
            openFileDialog1.Title = "Select a LarX Scene File to Merge";

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                Serializer.Merging = true;
                Serializer.Load(openFileDialog1.FileName);
            }
        }
        #endregion        

        #region ContextMenu RenderControl
        public static bool ContextMenuOpened;
        private void editorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ContextMenuOpened = true;
            editorToolStripMenuItem.DropDownItems.Clear();
            if (renderControl1.Manager != null)
            {
                if (renderControl1.Manager.SelectedActor != null)
                {
                    Actor selectedActor = renderControl1.Manager.SelectedActor;
                    editorToolStripMenuItem.DropDownItems.Add("Selected Actor");
                    editorToolStripMenuItem.DropDownItems[editorToolStripMenuItem.DropDownItems.Count - 1].Click += new EventHandler(actor_Click);
                    if (selectedActor.Parent != null)
                    {
                        ToolStripMenuItem objectParent = new ToolStripMenuItem("Actor - Object Parent");
                        objectParent.Click += new EventHandler(parent_Click);
                        editorToolStripMenuItem.DropDownItems.Add(objectParent);
                    }
                    if (selectedActor.ComponentParent != null)
                    {
                        ToolStripMenuItem componentParent = new ToolStripMenuItem("Actor - Component Parent");
                        componentParent.Click += new EventHandler(componentParent_Click);
                        editorToolStripMenuItem.DropDownItems.Add(componentParent);
                    }
                    if (selectedActor.Entity != null)
                    {
                        ToolStripMenuItem entityParent = new ToolStripMenuItem("Actor - Entity");
                        entityParent.Click += new EventHandler(entityParent_Click);
                        editorToolStripMenuItem.DropDownItems.Add(entityParent);
                    }
                }
            }
        }
        void entityParent_Click(object sender, EventArgs e)
        {
            if (renderControl1.Manager.SelectedActor != null)
            {
                if (renderControl1.Manager.SelectedActor != null &&
                    renderControl1.Manager.SelectedActor.Entity != null)
                {
                    propertyGrid.SelectedObject = renderControl1.Manager.SelectedActor.Entity;
                }
            }
        }
        void componentParent_Click(object sender, EventArgs e)
        {
            if (renderControl1.Manager.SelectedActor != null)
            {
                if (renderControl1.Manager.SelectedActor != null &&
                    renderControl1.Manager.SelectedActor.ComponentParent != null)
                {
                    propertyGrid.SelectedObject = renderControl1.Manager.SelectedActor.ComponentParent;
                }
            }
        }
        void actor_Click(object sender, EventArgs e)
        {
            if (renderControl1.Manager.SelectedActor != null)
            {
                if (renderControl1.Manager.SelectedActor != null)
                {
                    propertyGrid.SelectedObject = renderControl1.Manager.SelectedActor;
                }
            }
        }
        void parent_Click(object sender, EventArgs e)
        {
            if (renderControl1.Manager.SelectedActor != null)
            {
                if (renderControl1.Manager.SelectedActor != null &&
                    renderControl1.Manager.SelectedActor.Parent != null)
                {
                    propertyGrid.SelectedObject = renderControl1.Manager.SelectedActor.Parent;
                }
            }
        }
        private void contextMenuStrip1_Closing(object sender, ToolStripDropDownClosingEventArgs e)
        {
            ContextMenuOpened = false;
        }
        #endregion       

        #region Animation
        public void SetFrames(int min, int max)
        {
            keyFramesTrackBar.Maximum = max;
            keyFramesTrackBar.Minimum = min;

            label_EndFrame.Text = keyFramesTrackBar.Maximum.ToString();
            label_StartFrame.Text = keyFramesTrackBar.Minimum.ToString();
        }
        public int GetMaxFrames
        {
            get { return this.keyFramesTrackBar.Maximum; }
        }
        public int GetMinFrames
        {
            get { return this.keyFramesTrackBar.Minimum; }
        }

        private object selectedObject_WhenSetKey;
        private void anim_SetKey_Click(object sender, EventArgs e)
        {
            if (propertyGrid.SelectedObject is IKeyFramedAnimation)
            {
                /// If the Selected Object is an Animation Class
                if (propertyGrid.SelectedObject is Animation_Float)
                {
                    Animation_Float flo = propertyGrid.SelectedObject as Animation_Float;
                    flo.SetKey(this.keyFramesTrackBar.Value, flo.GetFloat());
                }
            }
            if (propertyGrid.SelectedObject is IAnimateableFloat)
            {
                /// If the Selected Object has an Animation Class
                PropertyInfo[] infos = propertyGrid.SelectedObject.GetType().GetProperties();
                selectedObject_WhenSetKey = propertyGrid.SelectedObject;

                int countOfAnimations = 0;
                for (int i = 0; i < infos.Length; i++)
                {
                    if (infos[i].Name.ToLower().Contains("animation") &&
                        infos[i].GetValue(propertyGrid.SelectedObject, null) is IKeyFramedAnimation)
                    {
                        countOfAnimations++;
                    }
                }

                if (countOfAnimations <= 1)
                {
                    IAnimateableFloat flo = propertyGrid.SelectedObject as IAnimateableFloat;
                    flo.Animation.SetKey(this.keyFramesTrackBar.Value, flo.Animation.GetFloat());
                }
                else
                {
                    context_SetKey.Items.Clear();
                    for (int i = 0; i < infos.Length; i++)
                    {
                        if (infos[i].Name.ToLower().Contains("animation") &&
                            infos[i].GetValue(propertyGrid.SelectedObject, null) is IKeyFramedAnimation)
                        {
                            context_SetKey.Items.Add(infos[i].Name, null, new EventHandler(OnClick_ContextSetKey));
                        }
                    }
                    context_SetKey.Visible = true;
                }
                //IAnimateableFloat flo = (IAnimateableFloat)propertyGrid.SelectedObject;

                //IAnimateableI3DObject dobj = (IAnimateableI3DObject)renderControl1.Manager.SelectedActor;
                //dobj.Animation.SetKey(keyFramesTrackBar.Value, dobj.Position, dobj.RadiansRotation, dobj.Scale);
            }
        }
        public void OnClick_ContextSetKey(object sender, EventArgs args)
        {
            if (propertyGrid.SelectedObject == selectedObject_WhenSetKey)
            {
                PropertyInfo[] infos = propertyGrid.SelectedObject.GetType().GetProperties();
                for (int i = 0; i < infos.Length; i++)
                {
                    if (infos[i].Name.ToLower().Contains((sender as ToolStripMenuItem).Text.ToLower()) &&
                        infos[i].GetValue(propertyGrid.SelectedObject, null) is IKeyFramedAnimation)
                    {
                        IAnimateableFloat flo = (IAnimateableFloat)infos[i].GetValue(propertyGrid.SelectedObject, null);
                        flo.Animation.SetKey(this.keyFramesTrackBar.Value, flo.Animation.GetFloat());
                    }
                }
            }
        }

        private KeyFrame_I3DObject CopyPasteFrame;
        private void anim_CopyKey_Click(object sender, EventArgs e)
        {
            if (renderControl1.Manager.SelectedActor != null)
            {
                IAnimateableI3DObject dobj = (IAnimateableI3DObject)renderControl1.Manager.SelectedActor;
                CopyPasteFrame = dobj.Animation.FrameByNumber(keyFramesTrackBar.Value);
            }
        }
        private void anim_PasteKey_Click(object sender, EventArgs e)
        {
            if (renderControl1.Manager.SelectedActor != null && CopyPasteFrame != null)
            {
                IAnimateableI3DObject dobj = (IAnimateableI3DObject)renderControl1.Manager.SelectedActor;
                dobj.Animation.SetKey(CopyPasteFrame.Frame, CopyPasteFrame.Position, 
                    CopyPasteFrame.Rotation, CopyPasteFrame.Scale);
            }
        }
        private void anim_Configure_Click(object sender, EventArgs e)
        {
            ConfigureAnim anim = new ConfigureAnim(this);
            anim.Show();
        }
        private void anim_Save_Click(object sender, EventArgs e)
        {
            if (renderControl1.Manager.SelectedActor != null)
            {
                IAnimateableI3DObject obj = (IAnimateableI3DObject)renderControl1.Manager.SelectedActor;
                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter = "LarX Animation Files|*.laranim";
                saveFileDialog1.Title = "Select a LarX Animation File";

                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    obj.Animation.Save(saveFileDialog1.FileName);
                }
            }     

        }
        private void anim_Load_Click(object sender, EventArgs e)
        {
            if (renderControl1.Manager.SelectedActor != null)
            {
                IAnimateableI3DObject obj = (IAnimateableI3DObject)renderControl1.Manager.SelectedActor;
                OpenFileDialog openFileDialog1 = new OpenFileDialog();
                openFileDialog1.Filter = "LarX Animation|*.laranim";
                openFileDialog1.Title = "Select a LarX Animation File";

                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    obj.Animation.Load(openFileDialog1.FileName);
                    keyFramesTrackBar.Maximum = obj.Animation.NumberOfFrames;
                }
            }
        }
        #endregion        

        private void renderControl1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == System.Windows.Forms.Keys.P)
            {
                Engine.PlayMode = !Engine.PlayMode;
            }
        }

        #region Options
        #region WPhone
        private void makeFontListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FontListMaker maker = new FontListMaker();
            maker.Show();
        }
        private void makeLanguageListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LanguageListMaker maker = new LanguageListMaker();
            maker.Show();
        }
        #endregion

        private void languageEditorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string[] args = new string[0];
            LanguageMainForm Lang = new LanguageMainForm(args);
            Lang.Show();
        }
        private void updateFileMakerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UpdateFileMakerForm form = new UpdateFileMakerForm();
            form.Show();
        }
        #endregion        

        #region Help
        
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LarX_Editor.About.AboutForm form = new About.AboutForm();
            form.Show();
        }

        #endregion

       

        #region 3DS Max Scene
        MaxSceneLinker linker;
        private void link3DSMaxSceneToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Do you want to connect to your 3DS Max Scene? You cannot save after pressing YES", 
                "WARNING", MessageBoxButtons.YesNo) ==
                DialogResult.Yes)
            {
                linker = new MaxSceneLinker(Engine.GameScreens[0], renderControl1.Renderer as Renderer_SunBurn);
                CanSave = false;
                //button_UpdateLinker.Visible = true;
            }
        }
        private void button_UpdateLinker_Click(object sender, EventArgs e)
        {
            linker.UpdateModel();
        }
        #endregion

        private bool setted;
        private Camera3D settedCamera;
        private void button_Camera_Click(object sender, EventArgs e)
        {
            if (!setted)
            {
                string cam = cam_textBox.Text;
                Camera3D camera = (Camera3D)EngineSystem.Component_ByName(cam);
                settedCamera = renderControl1.Camera;
                renderControl1.Camera = camera;
                setted = true;
            }
            else
            {
                renderControl1.Camera = settedCamera;
                setted = false;
            }
        }

        private void aIPointToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AIPoint point = new AIPoint((Renderer_SunBurn)renderControl1.Renderer, Engine.GameScreens[0]);
        }

        private void enemyAIToolStripMenuItem_Click(object sender, EventArgs e)
        {
            EnemyAI enemy = new EnemyAI((Renderer_SunBurn)renderControl1.Renderer, 
                AIState.Patrolling, Engine.GameScreens[0]);
        }

        private void animatedActorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                GameScreen Screen = (GameScreen)Engine.GameScreens[0];
                ActorPlayer Player = new ActorPlayer(
                    new sgMotionAnimatedActor("Engine\\AnimatedModels\\PlayerMarine"), renderControl1.Renderer, Screen);
            }
            catch (Exception exce)
            {
            }
        }


        private bool Moving;

        private void timer1_Tick(object sender, EventArgs e)
        {
            Mouse.WindowHandle = renderControl1.Handle;
            MouseState mouse = Engine.Input.MouseState;
            if (mouse.LeftButton == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
            {
                int X = mouse.X;
                int Y = mouse.Y;
                int offset = 15;
                if (X > renderControl1.Size.Width - offset &&
                    Y > renderControl1.Size.Height - offset &&
                    X < renderControl1.Size.Width + offset &&
                    Y < renderControl1.Size.Height + offset)
                {
                    Moving = true;
                }
            }
            else
                Moving = false;
            if (Moving)
            {
                renderControl1.Size = new Size(mouse.X, mouse.Y);
            }           
        }

        #region VisualScript

        #region Conditions
        private void timerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Editor != null)
            {
                Node_Timer timer = new Node_Timer(Editor.CurrentVisualScript);
                timer.StartRepresentation(Editor);
            }
        }
        private void alwaysToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Editor != null)
            {
                Node_Always always = new Node_Always(Editor.CurrentVisualScript);
                always.StartRepresentation(Editor);
            }
        }

        #endregion        

        #region Object
        private void selectedObjectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Editor != null && renderControl1.Manager != null &&
                renderControl1.Manager.SelectedActor != null)
            {
                Node_Object obj = new Node_Object(Editor.CurrentVisualScript);
                obj.Object = renderControl1.Manager.SelectedActor;
                obj.StartRepresentation(Editor);
            }
        }
        #endregion        

        #region Actors
        private void deleteActorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Editor != null)
            {
                Node_DeleteActor del = new Node_DeleteActor(Editor.CurrentVisualScript);
                del.StartRepresentation(Editor);
            }
        }
        private void sgMotionPlayToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Editor != null)
            {
                Node_sgAnimation sg = new Node_sgAnimation(Editor.CurrentVisualScript);
                sg.StartRepresentation(Editor);
            }
        }
        private void waveLipSyncToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Editor != null)
            {
                Node_WaveLipSync wave = new Node_WaveLipSync(Editor.CurrentVisualScript);
                wave.StartRepresentation(Editor);
            }

        }
        #endregion

        private void visualScriptToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (Editor != null)
            {
                VisualScript script = new VisualScript(Engine.GameScreens[0]);
                script.Visible = false;
                Editor.VisualScripts.Add(script);
            }
        }

        #endregion     

        private void checkppointToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Checkpoint checkpoint = new Checkpoint((Renderer_SunBurn)renderControl1.Renderer, Engine.GameScreens[0]);
        }

        private void takenHumanToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TakenHuman human = 
                new TakenHuman((Renderer_SunBurn)renderControl1.Renderer, AIState.Idle, Engine.GameScreens[0]);
            human.StartPosition = renderControl1.Camera.Position;
        }

        private void ratAleinToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RatAlien rat = 
                new RatAlien((Renderer_SunBurn)renderControl1.Renderer, AIState.Idle, Engine.GameScreens[0]);
            rat.StartPosition = renderControl1.Camera.Position;
        }

        private void sphereTriggerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SphereTrigger sphere = new SphereTrigger((Renderer_SunBurn)renderControl1.Renderer, 
                Engine.GameScreens[0]);
        }

        private void triangleMeshToolStripMenuItem_Click(object sender, EventArgs e)
        {
            BepuTrianglePlayer player = new BepuTrianglePlayer(
                new BepuEntity_TriangleMesh("Game\\Models\\Levels\\01_Proxy"),
                new Actor("Game\\Models\\Levels\\01"), (Renderer_SunBurn)renderControl1.Renderer, 
                Engine.GameScreens[0]);
        }

        private void arrayToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Array array = new Array(renderControl1.Manager.SelectedActor, renderControl1.Renderer.Camera);
            array.Show();
        }

        private void button_select_RenderEnvironment_Click(object sender, EventArgs e)
        {
            propertyGrid.SelectedObject = (renderControl1.Renderer as Renderer_SunBurn).Environment;
        }

        private void keyFramesTrackBar_Scroll(object sender, EventArgs e)
        {
            System.Drawing.Point k = keyFramesTrackBar.Location;
            Size size = keyFramesTrackBar.Size;
            label_ActualFrame.Location = new System.Drawing.Point(k.X, k.Y + 30);
            if (keyFramesTrackBar.Value > 0)
            {
                int max = keyFramesTrackBar.Maximum;
                int min = keyFramesTrackBar.Minimum;
                int final = max - min;
                int squareSize = keyFramesTrackBar.Size.Width / final;

                label_ActualFrame.Location = new System.Drawing.Point(label_ActualFrame.Location.X +
                    squareSize * (keyFramesTrackBar.Value - min), label_ActualFrame.Location.Y);
                label_ActualFrame.Text = keyFramesTrackBar.Value.ToString();
            }
            if (renderControl1.Manager != null &&
                renderControl1.Manager.SelectedActor != null)
            {
                renderControl1.Manager.SelectedActor.Anim_CurrentFrame = keyFramesTrackBar.Value;
            }
        }

        private void blurUtilitiesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            BlurUtilities util = new BlurUtilities((Renderer_SunBurn)renderControl1.Renderer, Engine.GameScreens[0]);
            (renderControl1.Renderer as Renderer_SunBurn).SceneInterface.PostProcessManager.AddPostProcessor(util);
            propertyGrid.SelectedObject = util;
        }

        private void propertyGrid_DoubleClick(object sender, EventArgs e)
        {
        }

        private void propertyGrid_Click(object sender, EventArgs e)
        {
        }

        private object mat;
        private void button_Matrix_Click(object sender, EventArgs e)
        {
            GridItem grid = propertyGrid.SelectedGridItem;
            mat = propertyGrid.SelectedObject;
            if (grid != null && grid.Value != null)
            {
                propertyGrid.SelectedObject = grid.Value;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            propertyGrid.SelectedObject = mat;
            mat = propertyGrid.SelectedObject;
        }
    }
}
